{{ header }}
<div id="account-order" class="container order-detail">
    {#{{ include(helper.template('_partial/breadcrumb')) }}#}
    {% if success %}
        <div class="alert alert-success alert-dismissible"><i class="fa fa-check-circle"></i> {{ success }}
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
    {% endif %}
    {% if error_warning %}
        <div class="alert alert-danger alert-dismissible"><i class="fa fa-exclamation-circle"></i> {{ error_warning }}
            <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
    {% endif %}
    <div class="row no-gutters">{{ column_left }}
        {% if column_left and column_right %}
            {% set class = 'col-sm-6' %}
        {% elseif column_left or column_right %}
            {% set class = 'col-sm-9' %}
        {% else %}
            {% set class = 'col-sm-12' %}
        {% endif %}
        <div id="content" class="account-order-content {{ class }}">{{ content_top }}
            {#<h2>{{ text_order_detail }}</h2>#}
            <table class="table first-order-info">
                <tbody>
                <tr>
                    <td class="text-left" style="width: 40%;">{% if invoice_no %}
                            <b>{{ text_invoice_no }}</b> {{ invoice_no }}<br/>
                        {% endif %} <b>{{ text_order_id }}</b> #{{ order_id }}<br/>
                        <b>{{ text_date_added }}</b> {{ date_added }}</td>
                    <td class="blank-td"></td>
                    <td class="text-left" style="width: 60%;">
                        {% if payment_method and not is_pending_payment %}
                            <b>{{ text_payment_method }}</b> {{ payment_method }}<br/>
                        {% endif %}
                        {% if shipping_address %}
                            <b>{{ text_shipping_address }}</b>
                            {{ shipping_address }}
                        {% endif %}
                    </td>
                </tr>
                </tbody>
            </table>
            <div>{{ order_should_sign_at }}</div>
            <div class="order-status">{{ column_status }}{{ colon }}{{ order_status }}</div>
            <div class="table-responsive clearfix">
                <table class="table table-bordered table-hover order-detail-info">
                    <thead>
                    <tr>
                        <td class="text-center">{{ column_product }}</td>
                        <td class="text-center">{{ column_model }}</td>
                        <td class="text-center count-td">{{ column_quantity }}</td>
                        <td class="text-center">{{ column_price }}</td>
                        <td class="text-center">{{ column_total }}</td>
						{% if order_completed %}
                        	<td class="text-center review">{{ text_review }}</td>
						{% endif %}
                        {% if products %}
                            <td class="text-center operation">{{ column_action }}</td>
                        {% endif %} </tr>
                    </thead>
                    <tbody>
                    {% for product in products %}
                        <tr>
                            <td class="text-center product-td">
                                <div class="product-info">
                                    <div class="product-image">
                                        <img src="{{ product.image }}" alt="">
                                    </div>
                                    <div class="product-text-info">
                                        <a href="{{ product.href }}" target="_blank">
                                            {{ product.name }}
                                        </a>
                                        {% for option in product.option %} <br/>
                                            <small> - {{ option.name }}: {{ option.value }}</small>
                                        {% endfor %}
                                    </div>
                                </div>
                            </td>
                            <td class="text-center">{{ product.model }}</td>
                            <td class="text-center">{{ product.quantity }}</td>
                            <td class="text-center">{{ product.price }}</td>
                            <td class="text-center">{{ product.total }}</td>
							{% if order_completed %}
								<td class="text-center">
									{% if product.review_action %}
										<a href="{{ product.review_action }}" class="btn btn-primary review">
											{{ text_review }}
										</a>
                                    {% else %}
										<span>{{ text_had_review }}</span>
									{% endif %}
								</td>
							{% endif %}
                            <td class="text-center" style="white-space: nowrap;">

                                {% if product.return %}
                                    <a href="{{ product.return }}" data-toggle="tooltip" title="{{ after_sale }}" class="btn btn-primary return-btn">
                                        {{ after_sale }}
                                    </a>
                                {% endif %}

								{% if product.reorder %}
                                    <a href="{{ product.reorder }}" data-toggle="tooltip" title="{{ button_reorder }}" class="btn btn-primary buy-again-btn">
                                        <img src="/catalog/view/theme/{{ helper.config('theme_default_directory') }}/image/icon_Shopping Cart@2x.png" alt="">
                                    </a>
								{% endif %}

                                {% if not (product.return or product.reorder ) %}
                                    -
                                {% endif %}


                            </td>
                        </tr>
                    {% endfor %}
                    {% for voucher in vouchers %}
                        <tr>
                            <td class="text-center">{{ voucher.description }}</td>
                            <td class="text-center"></td>
                            <td class="text-center">1</td>
                            <td class="text-center">{{ voucher.amount }}</td>
                            <td class="text-center">{{ voucher.amount }}</td>
                            {% if products %}
                                <td></td>
                            {% endif %} </tr>
                    {% endfor %}
                    </tbody>
                </table>
                <ul class="order-price pull-right">
                    {% for total in totals %}
                        {% if loop.last %}
                            <li>
                                <span class="text-center"><b>{{ total.title }}{{ colon }}</b></span>
                                <span class="text-center total-price">{{ total.text }}</span>
                            </li>
                        {% else %}
                            <li>
                                <span class="text-center"><b>{{ total.title }}{{ colon }}</b></span>
                                <span class="text-center">{{ total.text }}</span>
                            </li>
                        {% endif %}
                    {% endfor %}
                </ul>
            </div>
            {% if comment %}
                <table class="table table-bordered table-hover">
                    <thead>
                    <tr>
                        <td class="text-center">{{ text_comment }}</td>
                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                        <td class="text-center">{{ comment }}</td>
                    </tr>
                    </tbody>
                </table>
            {% endif %}
            {#{% if histories %}#}
            {#<h3>{{ text_history }}</h3>#}
            {#<table class="table table-bordered table-hover">#}
            {#<thead>#}
            {#<tr>#}
            {#<td class="text-left">{{ column_date_added }}</td>#}
            {#<td class="text-left">{{ column_status }}</td>#}
            {#<td class="text-left">{{ column_comment }}</td>#}
            {#</tr>#}
            {#</thead>#}
            {#<tbody>#}
            {#{% if histories %}#}
            {#{% for history in histories %}#}
            {#<tr>#}
            {#<td class="text-left">{{ history.date_added }}</td>#}
            {#<td class="text-left">{{ history.status }}</td>#}
            {#<td class="text-left">{{ history.comment }}</td>#}
            {#</tr>#}
            {#{% endfor %}#}
            {#{% else %}#}
            {#<tr>#}
            {#<td colspan="3" class="text-center">{{ text_no_results }}</td>#}
            {#</tr>#}
            {#{% endif %}#}
            {#</tbody>#}
            {#</table>#}
            {#{% endif %}#}
            {{ content_bottom }}</div>
        {{ column_right }}</div>

</div>

<!-- 模态框（Modal） -->
<div class="order-info-modal modal fade modal-vertical-middle" id="review-modal" tabindex="1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <form>
                    <div class="score">
                        {{ text_ration }}:
                        <i data-score="1" class="fa fa-star"></i>
                        <i data-score="2" class="fa fa-star"></i>
                        <i data-score="3" class="fa fa-star"></i>
                        <i data-score="4" class="fa fa-star"></i>
                        <i data-score="5" class="fa fa-star"></i>
                        <input type="hidden" name="rating">
                    </div>
                    <div>
                        <textarea name="text"></textarea>
                    </div>
                    <div class="images">
                        <label class="upload-btn text-center" for="upload_files">+</label>
                    </div>
                </form>
                <input type="file" id="upload_files">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary">{{ text_submit_review }}</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>

<!-- 预览模态框（Modal） -->
<div class="order-info-modal modal fade modal-vertical-middle" id="photo-modal" tabindex="1">
    <div class="modal-dialog">
    </div><!-- /.modal -->
</div>

{{ footer }}

<script>


    $(function () {

        var tipsText = '{{ text_operation_success }}';

        var $modal = $('#review-modal');
        var $start = $('#review-modal .score i');
        var $input = $('#review-modal input[name="rating"]');
        var $textarea = $('#review-modal textarea');
        var review_api = '';
        var $submitBtn = $('#review-modal .btn-primary');
        var $form = $('#review-modal form');
        var $currentBtn = null;

        // 上传图片
        var $upload_image = $('#upload_files');
        var image_urls = [];	// 存储上传之后的图片地址
        var upload_file_url = '/api/v1/app/common/file-manager';

        addCloseEventListener();

        $upload_image.on('change',function(){
            var files = this.files;
            if( !files || !files.length )return;

            var form_data = new FormData();

            form_data.append('file',files[0]);

            $.ajax({
                type: 'POST',
                url: upload_file_url,
                data: form_data,
                processData: false,
                contentType : false,
                dataType : 'json',
                success: function(res){
                    showImage(res.url);
                },
                error: function(error) {
                    layer.open({
                        skin: 'layer-alert',
                        btnAlign: 'c',
                        title: '',
                        content: error.message
                    });
                }
            })
        });

        /**
         * 创建标签，用于展示image
         * @param url 图片网址
         * */
        function showImage(url) {
            var tag_str = '<div class="single-image"><img src="' + url +'"><i data-index="' + image_urls.length + '" class="fa fa-close close-btn"></i><div class="mask"><i class="fa fa-eye"></i></div></div>';

            image_urls.push(url);
            insertTag($('.upload-btn'),tag_str);
        }

        /**
         * 插入标签
         * */
        function insertTag(origin_tag,tag) {
            origin_tag.before(tag);
        }

        /**
         * 给关闭按钮添加事件监听*/
        function addCloseEventListener() {
            $('body').on('click','.single-image .close-btn',function(e){
                var target = e.target;

                deleteImage(target.dataset.index);

                $upload_image.val('');
            })
        }

        /**
         * 删除图片
         * @param index 需要删除的图片的index值*/
        function deleteImage(index) {
            image_urls.splice(index,1);

            $('div').remove('.single-image');

            reRenderTag();
        }

        /**
         * 重新根据数组渲染生成新的dom*/
        function reRenderTag() {
            var tag_str = '';

            image_urls.forEach(function(url,index){
                tag_str += '<div class="single-image"><img src="' + url +'"><i data-index="' + index + '" class="fa fa-close close-btn"></i><div class="mask"><i class="fa fa-eye"></i></div></div>';
            });

            insertTag($('.upload-btn'),tag_str);
        }

        $('#account-order .review.btn').click(function (event) {
            event.preventDefault();
            if (!$(event.target).attr('disabled')){
                if( review_api !== $(event.target).attr('href') ){
                    resetAllReviewContent();
                    review_api = $(event.target).attr('href');
                }
                $modal.modal('show');
                $currentBtn = $(this);
            }
        });

        $start.on('click', function () {
            var score = parseInt($(this).attr('data-score'));
            $input.val(score);
            clearStars();
            $start.each(function (i, e) {
                if (score >= i+1){
                    $(e).addClass('selected');
                }
            });
        });

        $textarea.on('change', function () {
            // var length =  300 - $(this).val().length;
            // console.log()
        });

        // $modal.on('hide.bs.modal', function () {
        //     $start.each(function (i, e) {
        //         $(e).removeClass('selected');
        //     });
        // });

        $submitBtn.click(function () {
            var data = {};

            $.each($form.serializeArray(), function() {
                data [this.name] = this.value;
            });

            data.images = image_urls;
            asyncRequest(review_api, data, function () {
                $modal.modal('hide');
                var parent_td = $currentBtn.parent();
                $currentBtn.remove();
                parent_td.append('<span class="order-status">{{ text_had_review }}</span>');
                layer.open({
                    skin: 'layer-alert',
                    btnAlign: 'c',
                    title: '',
                    content: '{{ text_operation_success }}'
                });
            }, function (error) {
                layer.open({
                    skin: 'layer-alert',
                    btnAlign: 'c',
                    title: '',
                    content: error.message
                });
            });
        });

        // 清除所有的评价星星
        function clearStars() {
            $start.each(function(i, e){
                $(e).removeClass('selected');
            })
        }

        /**
         * 重置所有评价相关的内容
         * */
        function resetAllReviewContent() {
            clearStars();	// 清空评价星星
            $textarea.val('');	// 清空评价内容
            image_urls = [];	// 清空上传的图片数组
            $('div').remove('.single-image');	// 清空插入的img
        }

        /**
         * 异步请求
         * @param url
         * @param body
         * @param successFn
         * @param errorFn
         */
        function asyncRequest(url, body, successFn, errorFn) {
            $.ajax({
                url: url,
                type: 'POST',
                dataType: 'json',
                data: body,
                success: function (response) {
                    if (response.code !== 0) {
                        errorFn.call(null, new Error(response.error))
                    } else {
                        successFn.call(null, response);
                    }
                },
                error: function (error) {
                    errorFn.call(null, error)
                }
            });
        }

        /**
         *  监听已经被上传的图片的点击时事件
         */
        $('body').on('click', '.single-image .mask i',  function (event) {
            var img = $(event.currentTarget).parents('.single-image').children('img');
            if (img.attr('src')){
                previewImage(img.attr('src'));
            }
        });

        /**
         * 预览图片图片
         * @param src
         */
        function previewImage(src) {
            var $photoModal =  $("#photo-modal");
            $photoModal.find(".modal-dialog").html('');
            $photoModal.find('.modal-dialog').append("<img class='preview-image' src=\""+src+"\">");
            $photoModal.modal('show');
        }

        /**
         * 监听预览图片的模态框关闭的事件
         */
        $("#photo-modal").on('hide.bs.modal', function (event) {
            var $modal = $(event.currentTarget);
            $modal.find(".modal-dialog").html('');
        })

    });

</script>